<!-- components/Keypad.vue (优化字符显示) -->
<template>
  <view class="keypad">
    <view class="password-display" v-if="showPassword">
      <text
        v-for="(digit, index) in passwordLength"
        :key="index"
        class="password-dot"
        :class="{ 'filled': index < password.length }"
      ></text>
    </view>

    <view class="keypad-grid">
      <view
        v-for="key in keys"
        :key="key.value"
        class="key-item"
        :class="{ 'key-special': key.type === 'special' }"
        @tap="handleKeyPress(key)"
      >
        <text v-if="key.type !== 'backspace'">{{ key.label }}</text>
        <text v-else class="icon-backspace">{{ backspaceIcon }}</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, defineProps, defineEmits } from 'vue'

const props = defineProps({
  showPassword: {
    type: Boolean,
    default: true
  },
  passwordLength: {
    type: Number,
    default: 6
  }
})

// 使用兼容性更好的回退字符
const backspaceIcon = uni.getSystemInfoSync().platform === 'devtools' ? '⌫' : '删除'

const emit = defineEmits(['input', 'delete', 'confirm'])

const password = ref('')

const keys = [
  { label: '1', value: '1' },
  { label: '2', value: '2' },
  { label: '3', value: '3' },
  { label: '4', value: '4' },
  { label: '5', value: '5' },
  { label: '6', value: '6' },
  { label: '7', value: '7' },
  { label: '8', value: '8' },
  { label: '9', value: '9' },
  { label: '清空', value: 'clear', type: 'special' },
  { label: '0', value: '0' },
  { label: '删除', value: 'backspace', type: 'special' }
]

const handleKeyPress = (key) => {
  if (key.value === 'clear') {
    password.value = ''
    emit('input', password.value)
  } else if (key.value === 'backspace') {
    if (password.value.length > 0) {
      password.value = password.value.slice(0, -1)
      emit('delete', password.value)
    }
  } else {
    if (password.value.length < props.passwordLength) {
      password.value += key.value
      emit('input', password.value)

      // 达到指定长度时自动确认
      if (password.value.length === props.passwordLength) {
        setTimeout(() => {
          emit('confirm', password.value)
        }, 100)
      }
    }
  }
}

// 提供重置密码的方法
const resetPassword = () => {
  password.value = ''
}

// 暴露方法给父组件
defineExpose({
  resetPassword
})
</script>
